const redis = require('redis')
const { REDIS_CONF } = require('../conf/db')
// 创建客户端
const redisClient = redis.createClient(REDIS_CONF.port, REDIS_CONF.host)
// 添加错误事件监听器
redisClient.on('error', (err) => {
  console.error('Redis Client Error:', err)
})
// 连接数据库，启动之后立即执行
!(async function () {
  try {
    await redisClient.connect()
    console.log('redis connected success')
  } catch (err) {
    console.log('Redis connection error:', err)
  }
})()
// !(async function () {
//   await redisClient
//     .connect()
//     .then(() => {
//       console.log('redis connected success')
//     })
//     .catch((err) => {
//       console.log('Redis connection error:', err)
//     })
// })()
// set
async function set(key, val) {
  let objVal
  if (typeof val === 'object') {
    objVal = JSON.stringify(val)
  } else {
    objVal = val
  }
  try {
    return await redisClient.set(key, objVal, redis.print)
  } catch (error) {
    console.error('Redis set error:', error)
    throw error
  }
}

// get
async function get(key) {
  try {
    let val = await redisClient.get(key)
    if (val === null) return val
    try {
      val = JSON.parse(val)
    } catch (error) {
      // 如果解析失败，返回原始值
      return val
    }
    return val
  } catch (error) {
    console.error('Redis get error:', error)
    throw error
  }
}
module.exports = { set, get }
